package seig.wjy.filter;

import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import seig.wjy.domain.vo.LoginUser;
import seig.wjy.tools.JwtUtil;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * 每个请求只执行一次
 *
 * @author wu
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String uri = request.getRequestURI();
        // 放行登录请求
        String[] loginRequest = new String[]{"/login", "/logout", "/register"};
        for (String str : loginRequest) {
            if (uri.contains(str)) {
                filterChain.doFilter(request, response);
                return;
            }
        }
        // 验证token
        String token = request.getHeader("Authorization");
        if (!StringUtils.hasText(token)) { // token !=null&&token.length>0
            System.out.println("token为空");
        }
        // 校验令牌
        LoginUser loginUser = null;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            String loginUserString = claims.getSubject();
            // 把JSON字符串转换成User对象
            loginUser = JSON.parseObject(loginUserString, LoginUser.class);
        } catch (Exception e) {
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.write("token校验失败");
            out.flush();
            out.close();
            throw new RuntimeException("token校验失败");
        }
        // 把验证完信息放到springSecurity的上下文
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
        filterChain.doFilter(request, response);
    }
}
